// 图片预览
app.directive('thumbsList', function() {
    return {
        restrict: 'EA',
        link: function(scope, element, attr, controller) {
            if (scope.$last == true) {
                attr.$observe('targetHref', function(newValue) {
                    $('#gallery'+attr.thumbsList).remove();
                    $('#' + attr.thumbsList + " a").touchTouch(attr.thumbsList);
                });
            }
        }
    };
});
//搜索
app.directive('searchBox', function(httpService,$timeout) {
    return {
        restrict: 'EA',
        replace: true,
        // template:'{{searchListData}}',
        templateUrl: 'views/directiveTemplate/search.html',
        link: function(scope, element, attr, controller) {
            if(!scope.searchModel){
                scope.searchModel = [];
            }
            element.on('click', '.sl-item', function() {
                var obj = {
                    "Id": $(this).attr("key"),
                    "Name": $(this).attr("value"),
                    "type":$(this).attr("type")
                }
                var newArr = scope.searchModel.filter(function(item) {
                    return item.Id == obj.Id && item.Name == obj.Name;
                })
                var isRadio=$(this).attr("is-radio");
                if (newArr.length < 1) {
                    if(isRadio){
                        $(this).siblings(".sl-item").removeClass("active");
                    }
                    $(this).addClass("active");
                    utilities.safeApply(scope, function() {
                        if(isRadio){
                            _.remove(scope.searchModel, function(n) {
                              return n.type==obj.type;
                            });//如果是单选，移除同类别的已选条件
                        }
                        scope.searchModel.push(obj);
                    });
                } else {
                    var arr = scope.searchModel;
                    var resultIndex = null;
                    arr.forEach(function(item, index) {
                        if (angular.equals(obj, item)) {
                            resultIndex = index;
                        }
                    });
                    arr.splice(resultIndex, 1);
                    //去除active样式
                    $(this).removeClass("active");
                    //去除数组中的值
                    utilities.safeApply(scope, function() {
                        scope.searchModel = arr;
                    });
                }
                scope.$eval(attr.searchSubmit);
            });
            element.on('click', '.search-menu', function() {
                $(this).toggleClass('on');
                $('.search-condition').slideToggle();
            });
            /*element.on('click','.sl-param',function(){
                var obj={
                    "id":$(this).attr("key"),
                    "name":$(this).attr("value")
                };
                var arr=scope.searchModel;
                var resultIndex=null;
                arr.forEach(function(item,index){
                    if(angular.equals(obj,item)){
                        resultIndex=index;
                    }
                });
                arr.splice(resultIndex,1);
                //去除active样式
                $('.sl-item[key="'+$(this).attr("key")+'"]').removeClass("active");
                //去除数组中的值
                utilities.safeApply(scope,function(){
                    scope.searchModel=arr;
                });
            })*/
            scope.keyUp = function($event) {
                if ($event.keyCode == 13) { //回车
                    scope.$eval(attr.searchSubmit); //按键回车键搜索
                }
            }
            scope.searchSubmit = function() {
                scope.$eval(attr.searchSubmit);
            }
            /*var timer=$timeout(function(){
                element.find("input").focus();
                $timeout.cancel(timer);
            },0, false);*/
        }
    };
});
app.directive('repeatList', function($timeout) {
    return {
        restrict: 'EA',
        link: function(scope, elm, attr) {
            elm.on('click', 'li', function() {
                if (!attr.repeatList)
                    return
                    //设置样式
                $(this).siblings().removeClass("active");
                $(this).addClass("active");
                //设置值并执行方法
                var activeId = $(this).attr("relativeId");
                utilities.safeApply(scope, function() {
                    scope.activeId = activeId;
                });
            })
            attr.$observe('activeId', function(newValue) {
                if (newValue) {
                    scope.$eval(attr.repeatList);
                }
            });
        }
    };
});
//下拉加载
app.directive('whenScrolled', function($timeout) {
    return {
        restrict: 'EA',
        link: function(scope, elm, attr) {
            var raw = elm[0];
            elm.bind('scroll', function() {
                if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
                    scope.$eval(attr.whenScrolled);
                }
            });
        }
    };
});
//上传
app.directive('uploaderFile', function(FileUploader, QiniuToken, $compile, $parse, $localStorage,toaster) {
    return {
        restrict: 'EA',
        scope: {
            imgArr: "=ngModel",
        },
        link: function(scope, elm, attr) {
            scope.token_key = "";
            var uploader = scope.uploader = new FileUploader({
                url: 'http://upload.qiniu.com',
            });
            var html = [];
            var type = attr.type;
            var accept;
            var typeTxt;
            switch (type) {
                case "img":
                    accept = "image/gif,image/jpeg,image/jpg,image/png";
                    typeTxt = "图片上传";
                    break;
            }
            html.push('<div class="input-group">');
            html.push('<a href="javascript:void(0)" onclick="angular.element(' + "'#upload_input'" + ').click()"><i class="fa fa-upload"></i><span>上传图片</span></a>');
            html.push('<input id="upload_input" class="hidden_input" type="file" nv-file-select="" uploader="uploader" accept="' + accept + '" multiple>');
            html.push('<div class="img-list clearfix"><div class="img-box" ng-repeat="item in imgArr track by $index"><i ng-click="removeImg($index)" class="glyphicon glyphicon-remove remove-img"></i><img ng-src="{{item.Url}}"></div></div>');
            elm.append($compile(html.join(''))(scope));
            uploader.onAfterAddingFile = function(item) {
                //如果没有token先请求token
                if (!$localStorage.qiniuToken) {
                    QiniuToken.getToken(function() {
                        var timestamp = new Date().getTime();
                        var token = $localStorage.qiniuToken;
                        item.formData.push({ "key": timestamp, "token": $localStorage.qiniuToken });
                        uploader.uploadItem(item);
                    });
                } else {
                    var timestamp = new Date().getTime();
                    var token = $localStorage.qiniuToken;
                    item.formData.push({ "key": timestamp, "token": $localStorage.qiniuToken });
                    uploader.uploadItem(item);
                }
            }
            uploader.onSuccessItem = function(fileItem, response, status, headers) {
                if (attr.ngModel) {
                    utilities.safeApply(scope, function() {
                        if (!scope.imgArr) {
                            scope.imgArr = [];
                        }
                        scope.imgArr.push({ Url: $localStorage.Domain + response.key,key:response.key});
                    });
                }
            };
            uploader.onErrorItem = function(fileItem, response, status, headers) {
                console.info('onErrorItem', fileItem);
            };
            uploader.onCompleteAll = function() {
                uploader.clearQueue();
            };
            scope.removeImg=function(index){
                var key=scope.imgArr[index].key;
                if(key){
                    QiniuToken.delImg(key,function(){
                        utilities.safeApply(scope, function() {
                            scope.imgArr.splice(index, 1);
                        });
                    });
                }else{
                    toaster.error("图片不能删除");
                }
            }
        }
    };
});
app.directive('fileinput', function($rootScope,FileUploader, QiniuToken, $compile, $parse, $localStorage,httpService,toaster) {
    return {
        restrict: 'EA',
        scope:{
            item:"="
        },
        link: function(scope, elm, attr) {
            scope.uploadInit=function(token,imgArr,configArr){
                // $(".fileUpload").fileinput("clear");
                $(".fileUpload").fileinput({
                    uploadUrl: 'http://upload.qiniu.com',
                    allowedFileExtensions: ["jpg", "png", "gif","jpeg"],
                    uploadExtraData:{ "key": new Date().getTime(), "token": token},
                    showUpload: false,
                    showRemove:false,
                    browseClass: "btn btn-primary", //按钮样式
                    dropZoneEnabled:false,
                    fileActionSettings:{
                        showZoom:false,
                    },
                    maxFileCount:attr.maxFileCount,
                    // elErrorContainer: "#errorBlock"
                    initialPreview: imgArr,
                    initialPreviewAsData: true,
                    initialPreviewConfig: configArr,
                    deleteUrl: CONFIG.basePath+attr.deleteUrl,
                    deleteExtraData:{"Icon":""},
                    overwriteInitial: false,
                    maxFileSize: 1024,
                    language:'zh',
                }).on('filebatchselected',function(){

                }).on('fileuploaded', function(event, data, previewId, index) {
                    $('#uploadModal').modal('hide');
                    var resultData=data.response;
                    if(resultData.key){
                        httpService.request("PUT", attr.uploadUrl+attr.uploadId,{"Icon": $localStorage.Domain+resultData.key}, function(result) {
                            toaster.pop("success", "提示", result.message);
                            utilities.safeApply(scope, function() {
                                scope.item.Icon=$localStorage.Domain+resultData.key;
                                //同步头像
                                if($localStorage.userInfo.id==attr.uploadId){
                                    $rootScope.userInfo.icon=angular.copy(scope.item.Icon);
                                }
                            });
                        });
                    }
                }).on('filedeleted', function(event, key) {
                    utilities.safeApply(scope, function() {
                        scope.item.Icon="";
                        toaster.pop("success", "提示", "图片删除成功");
                    });
                });
            }
            scope.appendHtml=function(){
                var html = [];
                html.push('<div class="modal fade" id="uploadModal">');
                html.push('  <div class="modal-dialog '+attr.modalClass+'">');
                html.push('      <div class="modal-content">');
                html.push('          <div class="modal-header">');
                html.push('             <button type="button" class="close" data-dismiss="modal">');
                html.push('                 <span aria-hidden="true">&times;</span> <span class="sr-only">Close</span>');
                html.push('             </button>');
                html.push('             <h4 class="modal-title">图片上传</h4>');
                html.push('         </div>');
                html.push('         <div class="modal-body">');
                if(attr.isMultiple){
                    html.push('             <input name="file" class="fileUpload" type="file" class="file-loading" Multiple>');
                }else{
                    html.push('             <input name="file" class="fileUpload" type="file" class="file-loading">');
                }
                html.push('         </div>');
                html.push('       </div>');
                html.push('     </div>');
                html.push('   </div>');
                html.push('</div>');
                $('.main-con').after($compile(html.join(""))(scope));
                $('#uploadModal').modal('show');
            }
            elm.on('click', function(event) {
                $('#uploadModal').remove();
                scope.appendHtml();
                event.stopPropagation();
                var imgArr=[];
                var configArr=[];
                var token = $localStorage.qiniuToken;
                if(scope.item&&scope.item.Icon){
                    if(scope.item.Icon instanceof Array){
                        imgArr=scope.item.Icon;

                    }else{
                        imgArr=[scope.item.Icon];
                    }
                    imgArr.forEach(function(item, index) {
                        configArr.push({
                            "width":"120px",
                            key: 1
                        })
                    });
                }
                //如果没有token先请求token
                if (!token) {
                    QiniuToken.getToken(function() {
                        scope.uploadInit($localStorage.qiniuToken,imgArr,configArr);
                    });
                } else {
                    scope.uploadInit(token,imgArr,configArr);
                }
            });
        }
    };
});
//图形组件
app.directive('charts', function($timeout) {
    return {
        restrict: 'EA',
        link: function(scope, elm, attr) {
            var textWatch = scope.$watch(attr.charts, function(newVal, oldVal) {
                if (newVal!=null) {
                    var myChart = echarts.init(elm[0]);
                    myChart.setOption(newVal);
                    // textWatch();
                }
            });
        }
    };
});
